<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span{
            margin: 0 40px;
        }
        li{
            margin-top: 10px;
            padding-left: 10px;
            width: 400px;
            background-color: pink;
        }
        h1{
            padding-left: 160px;
        }
    </style>
</head>
<body>
    <input type="text" id="add">
    <hr>
    <h1>留言板</h1>
    <ul id="box"></ul>
</body>
</html>
<script>
    class Word{
        constructor(options){
            //获取元素
            this.add=document.querySelector(options.add)
            this.box=document.querySelector(options.box)
            this.list=JSON.parse(localStorage.getItem('list'))||[]
            //调用方法
            this.addInp()
            this.show()
            this.del()
        }
        //添加
        addInp(){
            //监听输入框
            this.add.addEventListener('keydown',(e)=>{
                //判断是否敲得是回车键
                if(e.code=='Enter'){
                   //非空校验
                   if(this.add.value==''){
                    return alert('内容不能为空')
                   }
                   let obj={title:this.add.value,time:new Date().toLocaleString()}
                   this.list.push(obj)
                   this.setCity()
                   this.show()
                   //清空输入框
                   this.add.value=''
                }
            })
        }
        // 储存本地
        setCity(){
            localStorage.setItem('list',JSON.stringify(this.list))
        }
        // 渲染
       show(){
            let str=''
            //遍历数组
            this.list.forEach((item,index)=>{
                str +=`
                    <li>
                    ${item.title} 
                    <span>${item.time}</span>
                    <button data-key="${index}">删除</button>   
                    </li>
                `
            })
            this.box.innerHTML=str
        }
        // 删除
         del(){
            //监听父盒子
            this.box.addEventListener('click',(e)=>{
                if(e.target.nodeName=='BUTTON'){
                    this.list.splice(e.target.dataset.key,1)
                    this.setCity()
                    this.show()
                }
            })
        }
    }
    new Word({
        add:'#add',
        box:'#box'
    })
</script>